<template>
  <div>
    <HeaderComponents/>
  </div>

  <div>
    <section class="discover-section">
      <!-- 左侧内容区 -->
      <div class="left-column">
        <div class="tab-bar">
          <a v-for="partition in partitions" :key="partition"
             :class="{ active: currentPartition === partition }"
             @click="selectPartition(partition)">
            {{ partition }}
          </a>
          <!-- 更多按钮 + 悬浮频道列表 -->
          <div class="more-btn" @click="toggleChannelDropdown">更多 ▾</div>
          <div :class="{ 'channel-dropdown': true, open: isChannelDropdownOpen }">
            <div class="channel-row" v-for="(row, index) in channelRows" :key="index">
              <span v-for="channel in row" :key="channel"
                    @click="selectPartition(channel)">
                {{ channel }}
              </span>
            </div>
          </div>
        </div>

        <!-- 帖子列表 -->
        <div v-if="loadingContent" class="loading">加载中...</div>
        <div v-else>
          <div v-for="content in partitionContents" :key="content.ctid"
     class="post"
     @click="jumpToContentDetail(content.ctid)"
     style="cursor: pointer">
  <div class="post-header">
    <div class="avatar"></div>
    <div class="post-info">
      <span class="name">{{ content.authorName }}</span>
      <span class="time">{{ formatTime(content.publishTime) }}</span>
    </div>
  </div>
  <div class="post-content">
    {{ content.title }}<br>
    {{ content.summary }}
  </div>
</div>

        </div>
      </div>


      <!-- 右侧侧边栏 -->
      <div class="right-column">
        <!-- 热点榜单 -->
        <div class="sidebar">
          <h3>热点榜单</h3>
          <ul>
            <li v-for="(hotContent, index) in hotContents" :key="index">
              <a @click="jumpToContentDetail(hotContent.ctid)">{{ index + 1 }}. {{ hotContent.title }}</a>
            </li>
          </ul>
        </div>

        <!-- 推荐用户模块放在热点榜单下面 -->
        <div class="sidebar">
          <h3>你可能感兴趣的人</h3>
          <ul>
            <li v-for="user in similarUsers" :key="user.uid">
              <a @click="jumpToUserProfile(user.uid)">
                <span class="user-avatar"></span>
                <span class="user-name">{{ user.userInput }}</span>
              </a>
            </li>
          </ul>
          <span class="refresh" @click="refreshInterestedPeople">换一换</span>
        </div>
      </div>

    </section>
  </div>
</template>

<script>
import axios from 'axios';
import dayjs from 'dayjs'; // 用于日期格式化
// 导入 SearchInput 组件
import SearchInput from '../../components/SearchInput.vue';
import { searchService } from '@/api/search';
import HeaderComponents from "@/components/HeaderComponents.vue";

export default {
  components:{
    HeaderComponents,
    SearchInput
  },
  data() {
    return {
      isChannelDropdownOpen: false,
      searchKeyword: '',
      currentPartition: '关注', // 默认选中"关注"分区
      partitions: ['印象', '同城', '情感', '时尚', '财经', '数码', '读书'], // 常用分区
      channelRows: [
        ['情感', '短剧', '文化', '周末', '电影', '社会', '电视剧', '美食'],
        ['国际', '深度', '财经', '读书', '摄影', '汽车', '颜值', '体育'],
        ['数码', '综艺', '时尚', '星座', '军事', '股市', '房产', '家居'],
        ['萌宠', '科技', '科普', '动漫', '运动健身', '旅游', '瘦身', '好物'],
        ['历史', '艺术', '美妆', '法律', '设计', '健康', '音乐', '新时代'],
        ['校园', '收藏', '政务', '育儿', '教育', '婚恋', '舞蹈', '辟谣'],
        ['公益', '三农']
      ],
      partitionContents: [], // 分区内容列表
      hotContents: [], // 热帖榜单
      user: null, // 当前登录用户
      longitude: null,
      latitude: null,
      loadingContent: false, // 加载内容中
      partitionCache: new Map(), // 分区内容缓存
      similarUsers: [], // 添加推荐用户列表

    };
  },
  created() {
    // 获取当前登录用户（假设从localStorage中获取）
    const userJson = localStorage.getItem('user');
    if (userJson) {
      this.user = JSON.parse(userJson);
    }
    // 加载默认分区内容
    this.selectPartition(this.currentPartition);

    // 加载热帖榜单
    this.loadHotContents();
    // 检查localStorage中是否有保存的推荐用户数据
    const savedSimilarUsers = localStorage.getItem('similarUsers');
    if (savedSimilarUsers) {
      this.similarUsers = JSON.parse(savedSimilarUsers);
    } else {
      // 加载推荐用户
      this.loadSimilarUsers();
    }
  },
  beforeDestroy() {
    // 在组件销毁时保存推荐用户数据到localStorage
    localStorage.setItem('similarUsers', JSON.stringify(this.similarUsers));
  },
  methods: {
    toggleChannelDropdown() {
      this.isChannelDropdownOpen = !this.isChannelDropdownOpen;
    },
    // 添加搜索处理方法
    handleSearch(keyword) {
      this.$router.push({
        name: 'SearchView',
        query: { keyword }
      });
    },
    selectPartition(partition) {
      console.log(`选择分区: ${partition}, 当前分区: ${this.currentPartition}`);

      // 允许用户重复点击相同分区（特别是同城分区）
      this.currentPartition = partition;
      this.isChannelDropdownOpen = false;

      // 检查缓存
      if (this.partitionCache.has(partition)) {
        console.log(`从缓存获取分区内容: ${partition}`);
        this.partitionContents = this.partitionCache.get(partition);
        return;
      }

      // 获取地理位置（仅限同城分区）
      if (partition === '同城') {
        // console.log("请求同城分区内容，需要获取地理位置...");
        this.fetchPartitionContents(partition);

        //   this.getUserLocation().then(() => {
        //     console.log("成功获取地理位置，开始请求分区内容");
        //     this.fetchPartitionContents(partition);
        //   }
        // ).catch(error => {
        //     console.error("获取地理位置失败:", error);
        //     // 即使失败也继续请求，使用默认值
        //     this.fetchPartitionContents(partition);
        //   });
      } else {
        this.fetchPartitionContents(partition);
      }
    },

    getUserLocation() {
      return new Promise((resolve, reject) => {
        if (navigator.geolocation) {
          console.log("浏览器支持地理位置服务，请求位置信息...");

          navigator.geolocation.getCurrentPosition(
              position => {
                console.log("成功获取地理位置");
                this.longitude = position.coords.longitude;
                this.latitude = position.coords.latitude;
                console.log(`经度: ${this.longitude}, 纬度: ${this.latitude}`);
                resolve();
              },
              error => {
                console.error('获取地理位置失败:', error);

                // 错误类型处理
                let errorMsg = "无法获取位置信息";
                switch(error.code) {
                  case error.PERMISSION_DENIED:
                    errorMsg = "用户拒绝了位置请求";
                    break;
                  case error.POSITION_UNAVAILABLE:
                    errorMsg = "位置信息不可用";
                    break;
                  case error.TIMEOUT:
                    errorMsg = "请求位置超时";
                    break;
                }

                console.error(errorMsg);
                this.longitude = 0;
                this.latitude = 0;
                reject(error);
              },
              {
                enableHighAccuracy: false, // 关闭高精度模式，可能更快
                timeout: 3000, // 增加超时时间到30秒
                maximumAge: 60000 // 允许使用一分钟内的缓存位置
              }
          );
        } else {
          // 浏览器不支持地理位置服务，尝试使用IP定位
          console.log("浏览器不支持地理位置服务，尝试使用IP定位...");
          axios.get('https://ipapi.co/json/')
              .then(response => {
                const location = response.data;
                this.longitude = location.longitude;
                this.latitude = location.latitude;
                console.log(`通过IP定位获取位置: 经度 ${this.longitude}, 纬度 ${this.latitude}`);
                resolve();
              })
              .catch(ipError => {
                console.error("IP定位失败:", ipError);
                this.longitude = 115.89;
                this.latitude = 28.68;
                resolve(); // 仍然继续
              });
        }
      });
    },
    fetchPartitionContents(partition) {
      if (!this.user || !this.user.uid) return;
      this.loadingContent = true;

      const params = {
        uid: this.user.uid,
        partitionName: partition,
        longitude: this.longitude || 115.89,
        latitude: this.latitude || 28.68
      };
      console.log('到这一步了？');
      axios.get('/api/pushPost/partition', { params })
          .then(response => {
            if (response.data.code === 200) {
              const contents = response.data.data || [];
              // 缓存分区内容
              this.partitionCache.set(partition, contents);
              this.partitionContents = contents;
              console.log('分区：'+partition);
              console.log('内容',contents);
            } else {
              console.error('获取分区内容失败:', response.data.message);
            }
          })
          .catch(error => {
            console.error('请求出错:', error);
          })
          .finally(() => {
            this.loadingContent = false;
          });
    },
    loadHotContents() {
      axios.get('/api/pushPost/hotContent')
          .then(response => {
            if (response.data.code === 200) {
              this.hotContents = response.data.data || [];
            }
          })
          .catch(error => {
            console.error('获取热帖榜单失败:', error);
          });
    },
    formatTime(time) {
      // 格式化时间
      return dayjs(time).format('YYYY-MM-DD HH:mm');
    },
    jumpToContentDetail(ctid) {
      this.$router.push({
        path: '/content',
        query: { ctid }
      });
    },
    likeContent(content) {
      // 点赞功能
      axios.post('/api/content/like', { ctid: content.ctid })
          .then(response => {
            if (response.data.code === 200) {
              content.likeCount++;
            }
          })
          .catch(error => {
            console.error('点赞失败:', error);
          });
    },
    // 加载推荐用户
    loadSimilarUsers() {
      if (!this.user || !this.user.uid) return;

      axios.get(`/api/pushPost/similarUser/${this.user.uid}`)
          .then(response => {
            if (response.data.code === 200) {
              this.similarUsers = response.data.data || [];
              console.log('推荐用户加载成功:', this.similarUsers);
            } else {
              console.error('获取推荐用户失败:', response.data.message);
            }
          })
          .catch(error => {
            console.error('获取推荐用户失败:', error);
          });
    },

    // 刷新推荐用户
    refreshInterestedPeople() {
      this.loadSimilarUsers();
    },

    // 跳转到用户个人主页
    jumpToUserProfile(uid) {
      console.log('跳转到用户主页:', uid);
      // 这里实现跳转到用户主页的逻辑
      window.location.href = `../previews/personCenter.html?uid=${uid}`;
    }

  }
};
</script>

<style src="../../assets/DiscoverPage.css"></style>
